package com.study.hot.jetpack.demo_words.ui

import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.study.hot.R
import com.study.hot.jetpack.demo_words.db.Words
import com.study.hot.jetpack.demo_words.viewmodel.WordsViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_words.wordsRv
import kotlinx.android.synthetic.main.fragment_words.*
import org.jetbrains.anko.sdk27.coroutines.onClick

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/04/05
 *     desc   :
 * </pre>
 */
class WordsFragment : Fragment() {

    private lateinit var wordsViewModel: WordsViewModel
    private lateinit var filterWords: LiveData<List<Words>>

    private lateinit var cardAdapter: WordsDiffAdapter
    private lateinit var normalAdapter: WordsDiffAdapter
    private lateinit var allWords: List<Words>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //在Fragment中使用menu，默认为不开启
        setHasOptionsMenu(true)
        return inflater.inflate(R.layout.fragment_words, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        wordsViewModel = ViewModelProvider(this)[WordsViewModel::class.java]
        cardAdapter = WordsDiffAdapter(wordsViewModel, true)
        normalAdapter = WordsDiffAdapter(wordsViewModel, false)
        wordsRv.adapter = cardAdapter
        filterWords = wordsViewModel.allWords
        filterWords.observe(requireActivity(), Observer {
            val itemCount = cardAdapter.itemCount
            cardAdapter.setWordsList(it)
            allWords = it
            normalAdapter.setWordsList(it)
            if (itemCount != it.size) {
                cardAdapter.notifyDataSetChanged()
                normalAdapter.notifyDataSetChanged()
            }
        })

        toAddBtn.onClick { v ->
            val navController = Navigation.findNavController(v!!)
            navController.navigate(R.id.action_wordsFragment_to_addWordsFragment)
        }

        ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START or ItemTouchHelper.END) {
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                //不处理拖拽事件
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val words = allWords[viewHolder.adapterPosition]
                wordsViewModel.deleteWords(words)
                Snackbar.make(wordsFragmentLayout, "删除一个单词", Snackbar.LENGTH_SHORT)
                        .setAction("撤销") {
                            wordsViewModel.insertWords(words)
                        }
                        .show()
            }

        }).attachToRecyclerView(wordsRv)
    }

    override fun onResume() {
        super.onResume()
        val inputManager = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(view?.windowToken, 0)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu_words, menu)
        //处理SearchView
        val searchView = menu.findItem(R.id.app_bar_search).actionView as SearchView
        searchView.maxWidth = 500
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                filterWords.removeObservers(requireActivity())
                filterWords = wordsViewModel.getWordsByEnglish(newText)
                filterWords.observe(requireActivity(), Observer {
                    val itemCount = cardAdapter.itemCount
                    cardAdapter.setWordsList(it)
                    normalAdapter.setWordsList(it)
                    allWords = it
                    if (itemCount != it.size) {
                        //使用带有diffutil功能的Adapter
                        /*cardAdapter.notifyDataSetChanged()
                        normalAdapter.notifyDataSetChanged()*/
                        cardAdapter.submitList(it)
                        normalAdapter.submitList(it)
                    }
                })
                return true
            }
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.clearAll -> {
                AlertDialog.Builder(requireContext()).apply {
                    setTitle("温馨提示")
                    setMessage("确定清空列表吗?")
                    setPositiveButton("确定") { _, _ -> wordsViewModel.deleteAllWords() }
                    setNegativeButton("取消") { _, _ -> }
                    show()
                }
            }
            R.id.changeStyle -> {
                if (wordsRv.adapter == normalAdapter) {
                    wordsRv.adapter = cardAdapter
                } else wordsRv.adapter = normalAdapter
            }
        }
        return super.onOptionsItemSelected(item)
    }
}